package com.fundcrawler.service.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fundcrawler.dto.FundValuationDTO;
import com.fundcrawler.entity.FundNav;
import com.fundcrawler.repository.FundNavRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class FundNavManager {
    @Autowired
    private FundNavRepository fundNavRepository;

    public Page<FundNav> findByFundCode(String code, Pageable pageable) {
        Page<FundNav> page = fundNavRepository.findByFundCode(code, pageable);
        return page;
    }

    public FundNav findLatestByFundCode(String code) {
        FundNav last = fundNavRepository.findLatestByFundCode(code);
        return last;
    }

    public long countDistinctFundCodes() {

        return fundNavRepository.countDistinctFundCodes();
    }

    public long count() {

        return fundNavRepository.count();
    }

    public List<FundNav> findAll() {
        return fundNavRepository.findAll();
    }

    public Page<FundNav> findAll(PageRequest pageable) {
        return fundNavRepository.findAll(pageable);
    }

    public void saveAll(List<FundNav> insertList, List<FundNav> updList) {
        fundNavRepository.saveAll(insertList);
        if(CollectionUtil.isNotEmpty(updList)){
            for(FundNav item : updList){
                FundNav fundNav = fundNavRepository.findByFundCodeDate(item.getFundCode(), item.getDate());
                fundNav.setUnitNav(item.getUnitNav());
                fundNav.setAccumulatedNav(item.getAccumulatedNav());
                fundNav.setDailyGrowth(item.getDailyGrowth());
                fundNavRepository.save(fundNav);
            }
        }
    }



    public List<FundValuationDTO> getValuationStats(String fundCode, Double unitNav) {

        List<Map> results = fundNavRepository.findValuationStatsRaw(fundCode, unitNav);
        List<FundValuationDTO> dtos = JSON.parseObject(JSON.toJSONString(results), new TypeReference<List<FundValuationDTO>>(){});


        return dtos;
    }
}
